package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeHandler implements Handler {
    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String content = "<!DOCTYPE html>" +
                "<html lang=\"zh-CN\">" +
                "<head>" +
                "    <meta charset=\"UTF-8\">" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                "    <title>服务器时间 - MiniWebSvr</title>" +
                "    <style>" +
                "        * { margin: 0; padding: 0; box-sizing: border-box; }" +
                "        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f7fa; padding: 40px; }" +
                "        .container { max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 10px; box-shadow: 0 3px 15px rgba(0,0,0,0.1); text-align: center; }" +
                "        h1 { color: #2c3e50; margin-bottom: 30px; }" +
                "        .time-display { font-size: 2.5rem; color: #e74c3c; margin: 30px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; font-family: 'Courier New', monospace; }" +
                "        .nav { margin-top: 30px; }" +
                "        .nav a { color: #3498db; text-decoration: none; margin: 0 10px; }" +
                "        .nav a:hover { text-decoration: underline; }" +
                "        .footer { margin-top: 30px; color: #7f8c8d; font-size: 0.9rem; }" +
                "    </style>" +
                "</head>" +
                "<body>" +
                "    <div class=\"container\">" +
                "        <h1>🕒 服务器时间</h1>" +
                "        <div class=\"time-display\">" + currentTime + "</div>" +
                "        <div class=\"nav\">" +
                "            <a href=\"/\">🏠 返回首页</a>" +
                "            <a href=\"/echo\">🔄 回显测试</a>" +
                "        </div>" +
                "        <div class=\"footer\">" +
                "            <p>MiniWebSvr - 轻量级Java Web服务器</p>" +
                "        </div>" +
                "    </div>" +
                "</body>" +
                "</html>";

        // TODO: [222024321072045/谢冈兵] 构造完整的 HTTP 响应头和响应体
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes().length);
        writer.println("Connection: close");
        writer.println();

        writer.println(content);
        writer.flush();
    }
}
